package com.frontop.bigdata.modules.controller;

import com.alibaba.fastjson.JSONObject;
import com.frontop.common.annotation.AnonymousAccess;
import com.frontop.common.util.ResultJsonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

/**
 * @author YangBoos
 * @title: WXTest
 * @projectName frontop-cloud
 * @description: TODO
 * @date 2022/1/20 16:26
 */
@RestController
public class WXTest {
    @Autowired
    RestTemplate restTemplate;

    @AnonymousAccess
    @PostMapping("/wxLogin")
    public ResultJsonUtil<Object> wxLogin(@RequestParam("code") String code){
        String AppId = "+" +
                "";  //公众平台自己的appId
        String AppSecret="21393c38526bbec805002854e1c96de6";  //AppSecret
        System.out.println("code:"+code);
        //公众号于小程序的接口不同
        //获取网页授权access_token
        JSONObject access_token_json = JSONObject.parseObject(restTemplate.getForObject("https://api.weixin.qq.com/sns/oauth2/access_token" +
                "?appid="+AppId +
                "&secret="+AppSecret+
                "&code="+code+
                "&grant_type=authorization_code", String.class));
        System.out.println("**access_token**:"+access_token_json);

        String access_token = access_token_json.getString("access_token");
//        //获取open_id
//        JSONObject open_id_json = JSONObject.parseObject(restTemplate.getForObject("https://api.weixin.qq.com/sns/jscode2session?" +
//                "appid="+AppId +
//                "&secret="+AppSecret +
//                "&js_code="+code +
//                "&grant_type=authorization_code", String.class));
//        System.out.println("**jsonData**:"+open_id_json);
        String openid = access_token_json.getString("openid");

        //获取用户信息
        String user_info = restTemplate.getForObject("https://api.weixin.qq.com/sns/userinfo?" +
                "access_token="+access_token +
                "&openid="+openid +
                "&lang=zh_CN", String.class);
        System.out.println("**user_info**:"+user_info);



        return new ResultJsonUtil().success(user_info);
    }

}
